import { createRouter, createWebHashHistory } from 'vue-router';
import Layout from './../views/Layout.vue';
import storage from '../utils/storage';
import api from '../api/index';
import utils from '../utils/utils';

const routes = [
  {
    path: '/',
    component: Layout,
    name: 'home',
    redirect: '/welcome',
    meta: { title: '首页' },
    children: [
      {
        path: '/welcome',
        name: 'welcome',
        component: () => import('@/views/Welcome.vue'),
        meta: { title: '欢迎页' },
      },
      // {
      //   path: '/system/user',
      //   name: 'user',
      //   component: () => import('@/views/system/User.vue'),
      //   meta: { title: '用户管理' },
      // },
      // {
      //   path: '/system/menu',
      //   name: 'menu',
      //   component: () => import('@/views/system/Menu.vue'),
      //   meta: { title: '菜单管理' },
      // },
      // {
      //   path: '/system/role',
      //   name: 'role',
      //   component: () => import('@/views/system/Role.vue'),
      //   meta: { title: '角色管理' },
      // },
      // {
      //   path: '/system/dept',
      //   name: 'dept',
      //   component: () => import('@/views/system/Dept.vue'),
      //   meta: { title: '部门管理' },
      // },
    ],
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('@/views/Login.vue'),
    meta: { title: '登录' },
  },
  {
    path: '/404',
    name: '404',
    component: () => import('@/views/404.vue'),
    meta: { title: '404' },
  },
];

const router = createRouter({
  // hash模式：createWebHashHistory，
  // history模式：createWebHistory
  // history: createWebHistory('/'),
  history: createWebHashHistory(),
  routes,
});

// 动态的加载路由
async function loadAsyncRoutes() {
  let userInfo = storage.getItem('userInfo', {});
  // 用户登录了在进行操作
  if (userInfo.token) {
    const { menuList } = await api.getUserMenu();
    let routes = utils.generateRoute(menuList);
    routes.map((route) => {
      let url = `./../views${route.component}.vue`;
      route.component = () => import(/* @vite-ignore */ url);
      router.addRoute('home', route);
    });
  }
}
await loadAsyncRoutes();

// 判断路由表中有没有路由数据
// 路由表是动态生成的
function checkPermission(path) {
  return router.getRoutes().filter((route) => route.path == path).length > 0 ? true : false;
}

// 导航守卫
router.beforeEach((to, from, next) => {
  // router.hasRoute(to.name)
  if (checkPermission(to.path)) {
    document.title = `${to.meta.title} - 通用后台管理系统`;
    next();
  } else {
    document.title = `$页面不见了 - 通用后台管理系统`;
    next('/404');
  }
});

export default router;
